package com.template.common.constant;

import com.alibaba.fastjson2.JSONObject;
import com.template.common.enums.SysCodeEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mltong
 */
@SuppressWarnings("serial")

@NoArgsConstructor
@Data
@Accessors(chain = true)
@Slf4j
public class CommonResult<T> implements Serializable {

	/**
	 * 状态码 200成功 500系统异常
	 */
	private int code;
	/**
	 * 描述信息
	 */
	private String message;
	/**
	 * 数据详情
	 */
	private T data;

	/**
	 * 请求日志ID
	 */
	private String reqId;

	public CommonResult(int code, String message, T data) {
		this.code = code;
		this.message = message;
		this.data = data;
		this.reqId = MDC.get(ConstantPool.LOG_ID);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("code", code);
		map.put("message", message);
		map.put("data", data);
		map.put("reqId", reqId);
		log.info("【※服务响应】|-response: " + JSONObject.toJSONString(map));
		if(code != SysCodeEnum.SUCCESS.getCode()){
			log.error("【※服务响应】|-response: " + JSONObject.toJSONString(map));
		}
	}

	/**
	 * 成功返回结果
	 */
	public static <T> CommonResult<T> success() {
		return new CommonResult<T>(SysCodeEnum.SUCCESS.getCode(), SysCodeEnum.SUCCESS.getMessage(), null);
	}
	/**
	 * 成功返回结果
	 *
	 * @param data 获取的数据
	 */
	public static <T> CommonResult<T> success(T data) {
		return new CommonResult<T>(SysCodeEnum.SUCCESS.getCode(), SysCodeEnum.SUCCESS.getMessage(), data);
	}
	/**
	 * 返回业务结果
	 *
	 * @param message 提示信息
	 */
	public static <T> CommonResult<T> failed(String message) {
		return new CommonResult<T>(SysCodeEnum.ERROR.getCode(), message, null);
	}
	/**
	 * 失败返回结果
	 *
	 * @param data
	 */
	public static <T> CommonResult<T> failed(T data) {
		return new CommonResult<T>(SysCodeEnum.ERROR.getCode(), SysCodeEnum.ERROR.getMessage(), data);
	}
	/**
	 * 返回业务结果
	 *
	 * @param message 提示信息
	 */
	public static <T> CommonResult<T> failed(int code, String message, T data) {
		return new CommonResult<T>(code, message, data);
	}


}
